import { useAppStoreWithOut } from "@/store/modules/app";
import NProgress from "../progress";
import { ElMessage } from "element-plus";
import router from "@/router";


export const headers = {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
}
// 请求拦截成功
export const requestUseSucc = (config: any) => {
    NProgress.start();
    const store = useAppStoreWithOut()
    if (store.getToken) {
        config.headers.Authorization = store.getToken
    }
    return config;
}

// 请求拦截失败
export const requestUseError = (err: any) => {
    //拦截失败
    return Promise.reject(err);
}

// 响应拦截成功 
export const responseUseSucc = (res: any) => {
    NProgress.done();
    if (res.data.code === -1) {
        ElMessage.error(res.data.message)
        return Promise.reject(res.data.message);
    }
    if (res.request.responseType === 'blob') {
        return res.data
    }
    return res.data.data

}

// 响应拦截失败
export const responseUseError = (err: any) => {
    NProgress.done();
    const msg = err.response.data.message
    if (msg) {
        ElMessage.error(msg)
    }
    if (err.response.status == 401) {
        router?.push('/login')
    }
    if (err.response.statusText) {
        ElMessage.error(err.response.statusText)
    }
    return Promise.reject(err);
}